package com.googlecode.contests_repo.core.model;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * A class whose purpose is to extract commonly used reflection code  
 * 
 * @author boyan
 */
public class ReflectionUtils {
	/**
	 * Sets all the annotated declared fields of a given object to a given value
	 * @param <U>
	 * @param <V>
	 * @param obj
	 * 		The object to inspect
	 * @param annotation
	 * 		The type of annotation to search for
	 * @param value
	 * 		The value to set the annotated fields to
	 */
	public static <U, V extends Annotation> void setAnnotatedFields(U obj, Class<V> annotation, Object value) {
		for (Field f : obj.getClass().getDeclaredFields()) {
			if (f.getAnnotation(annotation) != null) {
				try {
					new PropertyDescriptor(f.getName(), obj.getClass()).getWriteMethod().invoke(obj, value);
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				} catch (IntrospectionException e) {
					e.printStackTrace();
				}
			}
		}	
	}
}
